package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import coil3.compose.AsyncImagePainter.State
import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageScope

@Composable
fun MyImage(
    model: Any? = null,
    modifier: Modifier = Modifier,
    loading: @Composable (SubcomposeAsyncImageScope.(State.Loading) -> Unit) = {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
    },
) = SubcomposeAsyncImage(model = model, contentDescription = null, modifier = modifier, loading = loading)

/**
 * 支持手势缩放的图片
 * - 可使用手势拖动、放大、旋转图片
 * - 双击图片在 2倍 和 原始尺寸 切换
 * @param model Any?
 * @param modifier Modifier
 */
@Composable
fun TransformableImage(model: Any? = null, modifier: Modifier = Modifier) {
    // 缩放比例
    var scale by remember { mutableFloatStateOf(1f) }
    // 旋转角度
    var rotation by remember { mutableFloatStateOf(0f) }
    // 偏移量
    var offset by remember { mutableStateOf(Offset.Zero) }

    // 监听手势变化
    val state = rememberTransformableState(onTransformation = { zoomChange, offsetChange, rotationChange ->
        // 限制最大放大倍数为4倍
        scale = (zoomChange * scale).coerceAtMost(4f)
        rotation += rotationChange
        offset += offsetChange
    })

    SubcomposeAsyncImage(model = model, contentDescription = null, loading = { CircularProgressIndicator() }, modifier = modifier
        .transformable(state = state)
        .graphicsLayer(scaleX = scale, scaleY = scale, rotationZ = rotation, translationX = offset.x, translationY = offset.y)
        .pointerInput(Unit) {
            detectTapGestures(onDoubleTap = {
                scale = if (scale <= 1f) 2f else 1f
                offset = Offset.Zero
                rotation = 0f
            })
        })
}